package cn.buyclss.backend.interceptor;

import cn.buyclss.backend.annotation.RequiredPermission;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Cecurio
 * @create: 2019-02-10 14:48
 **/
public class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法上的注解
            RequiredPermission requiredPermission =
                handlerMethod.getMethod().getAnnotation(RequiredPermission.class);

            // 如果方法上的注解为空 则获取类的注解
            if (requiredPermission == null) {
                requiredPermission =
                    handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);
            }

            // 如果标记了注解，则判断权限
            if (requiredPermission != null) {
                System.out.println(requiredPermission.value());
                return true;
            }

        }
        response.getWriter().write("no admission ");
        response.getWriter().close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
